layui.use(['flow','form','layer','upload'],function(){
    var flow = layui.flow,
        form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        $ = layui.jquery,
        upload = layui.upload;

    //校验登录状态
    if(isNotLogIn()){
        return;
    }

    //流加载图片
    var imgNums = 5;  //单页显示图片数量
    flow.load({
        elem: '#Images', //流加载容器
        isLazyimg:true,
        done: function(page, next){ //加载下一页
            $.ajax({
                url : "/CivilAffairs/manager/getShowPic",
                type : "post",
                data : {"page":page,"number":imgNums},
                async : false,
                dataType : "json",
                success : function(result) {
                    if(checkResult(result)){
                        //模拟插入
                        var imgList = [];
                        var maxPic = result.data.count;
                        var pics = result.data.data;
                        for(var i=0;i<pics.length;i++){
                            imgList.push('<li itemid="'+pics[i].news_id+'"><img lay-src="'+ pics[i].news_pic_src +'"><div class="operate"><div class="check">' +
                                '<input type="checkbox" name="belle" lay-filter="choose" lay-skin="primary" ' +
                                'title="'+pics[i].news_title+'"></div><i class="layui-icon img_del">&#xe640;</i></div></li>')
                        }
                        next(imgList.join(''), page < (maxPic/imgNums));
                        form.render();
                    }
                },
                error : function(result) {
                    console.log("获取图片异常:"+result.status+","+result.statusMessage);
                    layer.msg("获取图片信息异常,请稍后重试", { icon: 2 });
                }
            });
        }
    });

    //显示添加图片区域
    var addNewPicHtml = "<div class=\"layui-inline\" style=\"width: 400px\">\n" +
        "\t\t\t\t<input id=\"newsTitle\" type=\"text\" name=\"title\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"请输入标题\" class=\"layui-input\">\n" +
        "\t\t\t</div>\n" +
        "\t\t\t<div class=\"layui-upload layui-inline\" style=\"width: 300px\">\n" +
        "\t\t\t\t<a type=\"button\" name=\"image\" class=\"layui-btn layui-btn-normal\" id=\"choosePic\">选择图片</a>\n" +
        "\t\t\t</div>\n" +
        "\t\t\t<div class=\"layui-upload layui-inline\" style=\"width: 80px\">\n" +
        "\t\t\t\t<a type=\"button\" class=\"layui-btn layui-btn-normal\" id=\"uploadPic\">确认添加</a>\n" +
        "\t\t\t</div>";
    var isShow = false;
    $("body").on("click","#addNewPic",function () {
        if(isShow){
            $("#newPicHtml").html("");
            isShow = false;
        }else{
            $("#newPicHtml").html(addNewPicHtml);
            isShow = true;
            //添加轮播图
            upload.render({
                elem: '#choosePic'
                ,url: '/CivilAffairs/manager/uploadPic'
                ,auto: false
                //,multiple: true//是否允许多文件上传
                ,drag:true //接受拖拽上传
                ,data:{newsTitle:function () {
                        return $("#newsTitle").val();
                    },
                    managerId:function () {
                        //校验登录状态
                        if(isNotLogIn()){
                            return "";
                        }
                        return getCookie("managerId");
                    }}
                ,accept:'images' //上传文件类型
                ,exts:'jpg|png|gif|jpeg' //上传文件后缀
                ,field:'image' //后台接收默认字段名
                ,bindAction: '#uploadPic'
                ,choose: function(obj) {
                    obj.preview(function(index, file, result) {
                        var img = new Image();
                        img.onload = function() {
                            console.log('choose poster', img.width, img.height);
                            if (480 == img.width && 360 == img.height) {
                                $('#upload_poster_preview').attr('src', result); //图片链接（base64）不支持ie8
                                obj.upload(index, file);
                            } else {
                                layer.msg('该图片大小不符合规格!图片大小需为： 480px,360px',{icon:2});
                                $("#addNewPic").click();
                                $("#addNewPic").click();
                            }
                        };
                        img.src = result;
                    });
                }
                ,done: function(result){ //done是单个上传完执行回调,如果是多图片上传,要使用Alldone来执行回调
                    if(checkResult(result)){
                        layer.msg(result.detail,{icon:6});
                        window.location.reload();
                    }
                    console.log(result)
                }
            });
        }

    });
    $("body").on('click', '#newPicHtml img', function() {
        window.open("./detail/index.html?id="+$(this).attr("itemid"));
    });

    //删除单张图片
    $("body").on("click",".img_del",function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var _this = $(this);
        layer.confirm('确定删除图片"'+_this.siblings().find("input").attr("title")+'"吗？',{icon:3, title:'提示信息'},
            function(index){
            var newsId = _this.parents("li").attr("itemid");
            deleteNews(newsId,_this);
            layer.close(index);
        });
    });

    //删除新闻
    function deleteNews(newsId,_this){
        $.ajax({
            url : "/CivilAffairs/manager/deleteNews",
            type : "post",
            data : {"newsId":newsId},
            async : false,
            dataType : "json",
            success : function(result) {
                if(checkResult(result)){
                    layer.msg(result.detail,{icon:6});
                    _this.parents("li").remove();
                    return true;
                }
                return false;
            },
            error : function(result) {
                reqError(result,"删除图片异常");
                return false;
            }
        });
    }

    //全选
    form.on('checkbox(selectAll)', function(data){
        var child = $("#Images li input[type='checkbox']");
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('#Images').find('li input[type="checkbox"]');
        var childChecked = $(data.elem).parents('#Images').find('li input[type="checkbox"]:checked');
        if(childChecked.length == child.length){
            $(data.elem).parents('#Images').siblings("blockquote").find('input#selectAll').get(0).checked = true;
        }else{
            $(data.elem).parents('#Images').siblings("blockquote").find('input#selectAll').get(0).checked = false;
        }
        form.render('checkbox');
    })

    //批量删除
    $(".batchDel").click(function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var $checkbox = $('#Images li input[type="checkbox"]');
        var $checked = $('#Images li input[type="checkbox"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的图片？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                //setTimeout(function(){
                    //删除数据
                    $checked.each(function(){
                        var newsId = $(this).parents("li").attr("itemeid");
                        var isDelete = deleteNews(newsId,$(this));
                        //setTimeout(function(){$(this).parents("li").remove();},950);
                    })
                    $('#Images li input[type="checkbox"]').prop("checked",false);
                    form.render();
                    layer.close(index);
                    layer.msg("删除成功");
                //},2000);
            })
        }else{
            layer.msg("请选择需要删除的图片");
        }
    })

});